/**
 *  
 * 背景音乐，默认为一种背景音乐
 * 调用play会停止掉之前的音乐启动新的音乐
 * 默认循环播放
 * 
 */
class SoundBackground extends BaseSound{
    /** 当前在播的背景音乐 */
    private currentSoundUrl:string;
    private currentSound :egret.Sound;
    private currentSoundChannel:egret.SoundChannel;
    private currentLoop :number;
    
	public constructor() {
        super();
        this.currentLoop =0;
	}
	
    public static get get(): SoundBackground {
        return SoundBackground.getInstance();
    }
	
	/**
     * 复写父类加载完成后播放动作
	 */
    public loadedPlay(source: string): void {
        super.loadedPlay(source);
        this.play(source);
    }
    
    /**
     * 复写父类，播放某个url
	 */
    public play(source: string): void {
        if(this.currentSoundUrl == source){
            return;
        }else{
            var sound = this.getSound(source);
            if(sound){
                this.currentSoundUrl =source;
            }
            this.playSound(sound,this.currentLoop); 
        }
    }
    
    /**
     * 停止当前音乐
     */
    public stop(): void {
        if(this.currentSoundChannel) {
            Log.d("Bg Sound Stop,Shange Another");
            this.currentSoundChannel.stop();
        }
        this.currentSoundChannel = null;
        this.currentSound = null;
    }
    
    /**
     * 复写播放某个声音
	 */
    public playSound(sound: egret.Sound,loop?: number): void {
        if(sound) {
            this.stop();
            this.currentSound = sound;
            this.currentSoundChannel= sound.play(0,this.currentLoop);
            this.currentSoundChannel.volume = this.volume;
            Log.d("Play Sound,Loop:" + loop + ",Volume:" + this.volume);
        } else {
            Log.d("Excute PlaySound(),Sound AsyncLoad ");
        }
    }
    
    
    public static test(): void {
        var bgSound = new SoundBackground();
        var source = "bg_intro_1_mp3";
        bgSound.play(source);
        
        var timer: egret.Timer = new egret.Timer(3500,5);
        var i = 0;
        timer.addEventListener(egret.TimerEvent.TIMER,()=>{
            Log.n();
            i ++;
            Log.d("TimerEvent.TIMER excute:" +egret.getTimer());
            if(i % 2==1){
                source = "bg_gamemain_2_mp3";
            }else{
                source = "bg_intro_1_mp3";
            }
            bgSound.play(source); 
            },this);
        
        timer.addEventListener(egret.TimerEvent.TIMER_COMPLETE,()=>{
            Log.n();
            Log.d("TimerEvent.TIMER_COMPLETE excute:" + egret.getTimer());
            },this);
        //开始计时
        timer.start();
    }
}
